package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;


/**
 * 处理社交登陆请求
 */
@Controller
@Slf4j
public class OAuth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {

        HashMap<String, Object> map = new HashMap<>();
        map.put("client_id", "258805992");
        map.put("client_secret", "9cedc9ce2f036e3fe458c06476eb1f07");
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://auth.gulimall.com/oauth2.0/weibo/success");
        map.put("code", code);
        // 1、根据code换取accessTokens
        String result = HttpUtils.postRequest("https://api.weibo.com/oauth2/access_token", null, map);
        // 2、处理
        if (result != null) {
            // 获取到了accessToken
            SocialUser socialUser = JSON.parseObject(result, SocialUser.class);

            //知道当前是哪个社交用户
            // 1、当前用户如果是第一次进网站，自动注册进来(为当前社交用户生成一个会员信息账号。以后这个社交账号就对应)
            // 登录或者注册这个社交用户bc
            R r = memberFeignService.oauthLogin(socialUser);
            if (r.getcode() == 0){
                MemberRespVo data = r.getData("data", new TypeReference<MemberRespVo>() {
                });
                log.info("登录成功，用户信息" + data.toString());
                session.setAttribute("loginUser",data);

                // 2、登陆成功就跳回首页
                return "redirect:http://gulimall.com";
            }else {
                System.out.println(r.getMessage());
                return "redirect:http://auth.gulimall.com/login.html";
            }

        } else {
            return "redirect:http://auth.gulimall.com/login.html";
        }

    }

}
